/**
 * Created by wdj on 16/5/24.
 * ${NAME}
 */

var qrcode,
    surlEl;

if (typeof chrome.tabs !== 'undefined') {
    chrome.tabs.getSelected(function (w) {

        surlEl = G('surl');

        toShortUrl(w.url).then(function (surl) {
            surlEl.value = surl;
            if (!qrcode) {
                qrcode = new QRCode("qr", {
                    text: surl,
                    width: 300,
                    height: 300,
                    colorDark: "#000000",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H
                });
            } else {
                qrcode.clear();
                qrcode.makeCode(surl);
            }
        }).catch(function (err) {
            surlEl.value = err;
        });

        surlEl.blur();
        G('onekeycopy').focus();
    });
}

G('onekeycopy').onclick = function () {
    var t = this;
    var copyDiv = G('surl');

    execCopy(copyDiv);

    t.innerHTML = '已复制到剪切板';
    t.style.backgroundColor = '#aaa';

    setTimeout(function () {
        t.innerHTML = '一键复制';
        t.style.backgroundColor = 'green';
    }, 1000);
};

function execCopy(copyDiv) {
    copyDiv.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
}

function toShortUrl(url) {

    var requestURL = 'https://50r.cn/short_url.json?ref=chrome_ext&url=' + encodeURIComponent(url);

    return new Promise(function (resolve, reject) {

        get(requestURL).then(function (data) {
            resolve(data.url);
        }).catch(function (err) {
            reject("Error: " + err);
        });

    });
}

function get(url) {

    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status === 200) {
                    var responseText = xhr.responseText;
                    var contentType = xhr.getResponseHeader("Content-Type");
                    if (contentType && contentType.indexOf('application/json') === 0) {
                        responseText = JSON.parse(responseText);
                        if (responseText.error) {
                            reject(responseText.error || 'error.');
                        }
                    }
                    resolve(responseText);
                } else {
                    reject(xhr.responseText || 'ajax error!');
                }
            }
        };
        xhr.open('get', url, true);
        xhr.send();
    });
}

function G(element) {
    return document.getElementById(element)
}
